/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.auth.granter;

import cn.hutool.core.util.StrUtil;
import org.springblade.auth.constant.AuthConstant;
import org.springblade.auth.service.BladeUserDetails;
import org.springblade.auth.utils.TokenUtil;
import org.springblade.core.redis.cache.BladeRedis;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.support.Kv;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.core.tool.utils.WebUtil;
import org.springblade.system.entity.User;
import org.springblade.system.entity.UserInfo;
import org.springblade.system.feign.IUserClient;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.provider.*;
import org.springframework.security.oauth2.provider.token.AbstractTokenGranter;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;

import javax.servlet.http.HttpServletRequest;
import java.util.LinkedHashMap;
import java.util.Map;

import static org.springblade.common.cache.CacheNames.cacheKey;

/**
 * 第三方登录认证类
 *
 * @author Chill
 */
public class PhoneTokenGranter extends AbstractTokenGranter {
	private static final String GRANT_TYPE = "phone";

	private static final String CAPTCHA_KEY = "blade:sms::captcha:";
	private static final Integer AUTH_SUCCESS_CODE = 2000;

	private final IUserClient userClient;

	private final BladeRedis bladeRedis;

	protected PhoneTokenGranter(AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory, IUserClient userClient, BladeRedis bladeRedis) {
		super(tokenServices, clientDetailsService, requestFactory, GRANT_TYPE);
		this.userClient = userClient;
		this.bladeRedis = bladeRedis;
	}

	@Override
	protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
		// 请求头租户信息
		HttpServletRequest request = WebUtil.getRequest();
		String tenantId = Func.toStr(request.getHeader(TokenUtil.TENANT_HEADER_KEY), TokenUtil.DEFAULT_TENANT_ID);

		Map<String, String> parameters = new LinkedHashMap<>(tokenRequest.getRequestParameters());
		// 授权类型
		String source = parameters.get("source");

		// 手机号码
		String phone = parameters.get("phone");

		// 验证码
		String code = parameters.get("code");

		// 验证码校验id
		String id = parameters.get("id");

		// 校验验证码是否正确
		String cache = bladeRedis.get(StrUtil.concat(false,CAPTCHA_KEY,phone,StrUtil.COLON, id));
		if (StringUtil.isNotBlank(code) && StringUtil.equalsIgnoreCase(cache, code)) {
			bladeRedis.del(StrUtil.concat(false,CAPTCHA_KEY,phone,StrUtil.COLON, id));
		} else{
			throw new InvalidGrantException("验证码校验错误");
		}


		// 远程调用，获取认证信息
		R<UserInfo> result = userClient.userInfo(tenantId,phone);
		BladeUserDetails bladeUserDetails;
		if (result.isSuccess()) {
			User user = result.getData().getUser();
			Kv detail = result.getData().getDetail();
			if (user == null || user.getId() == null || user.getAccount() == null) {
				throw new InvalidGrantException("phone grant failure, user is null");
			}
			bladeUserDetails = new BladeUserDetails(user.getId(),
				tenantId, result.getData().getOauthId(), user.getName(), user.getRealName(), user.getDeptId(), user.getPostId(), user.getRoleId(), Func.join(result.getData().getRoles()), Func.toStr(user.getAvatar(), TokenUtil.DEFAULT_AVATAR),
				phone, AuthConstant.ENCRYPT + user.getPassword(), detail, true, true, true, true,
				AuthorityUtils.commaSeparatedStringToAuthorityList(Func.join(result.getData().getRoles())));
		} else {
			throw new InvalidGrantException("social grant failure, feign client return error");
		}

		// 组装认证数据，关闭密码校验
		Authentication userAuth = new UsernamePasswordAuthenticationToken(bladeUserDetails, null, bladeUserDetails.getAuthorities());
		((AbstractAuthenticationToken) userAuth).setDetails(parameters);
		OAuth2Request storedOAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest);

		// 返回 OAuth2Authentication
		return new OAuth2Authentication(storedOAuth2Request, userAuth);
	}

}
